/**
 * 
 */
package com.mc.mqtt;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.RandomStringUtils;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import com.mc.okhttp.OkHttpUtil;

import cn.hutool.core.io.FileUtil;

/**
 * @author w.weizhen
 *
 */
public class ClientMethod {
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// 订阅消息
		String topic = "eNJ";
		// 信息内容
		String content = "68 10 10 68 03 07 22 02 32 01 31 2D 81 06 00 00 00 01 60 01 A8 16 ";
		// 消息等级：
		// 0 消息最多发送一次，在客户端离线或不可用时，客户端会丢失这条消息
		// 1 消息至少发送一次，保证客户端能收到这条消息
		// 2 消息仅传送一次
		int qos = 2;
		String serverURI = "tcp://218.94.157.226:9083";
		
		//客户端id，用于设置客户端会话的ID。在setCleanSession(false);被调用时，MQTT服务器利用该ID获得相应的会话。此ID应少于23个字符，默认根据本机地址、端口和时间自动生成
		String clientId = "";
		String userName = "hymqtt_broker01";
		String pwd = "Hy13!8260BniC";
		try {
			/**
			 * 不传递persistence默认使用文件保存未发送的消息，传递null使用内存保存未发送的消息
			 */
			MqttClient mqttClient = new MqttClient(serverURI, clientId, null);
			MqttConnectOptions connOpts = new MqttConnectOptions();
			/**
			 * 再次连接时是否清除上次的session，即重新连接时是否不接收未收到的消息。只有重新连接时才能够更改此参数
			 * 若设为false，MQTT服务器将持久化客户端会话的主体订阅和ACK位置，默认为true
			 */
			connOpts.setCleanSession(true);
			//服务器认证用户名
			connOpts.setUserName(userName);
			//服务器认证密码
			connOpts.setPassword(pwd.toCharArray());
			
			connOpts.setConnectionTimeout(10);
			//定义客户端传来消息的最大时间间隔秒数，服务器可以据此判断与客户端的连接是否已经断开，从而避免TCP/IP超时的长时间等待
			connOpts.setKeepAliveInterval(20);
			
			// 发起连接
			mqttClient.connect(connOpts);
			// 回调
			//MqttCallback callback = new MessageProcess();
			//mqttClient.setCallback(callback);
			mqttClient.setCallback(new MqttCallback() {
				//收到消息
				@Override
				public void messageArrived(String topic, MqttMessage message) throws Exception {
					System.out.println("收到消息,topic:"+topic+", message:"+message.toString());
				}
				//消息发送成功
				@Override
				public void deliveryComplete(IMqttDeliveryToken token) {
					System.out.println("消息发送成功!");
				}
				//链接丢失，链接断开
				@Override
				public void connectionLost(Throwable cause) {
					System.err.println("链接丢失了!");
				}
			});
			//订阅主题
			mqttClient.subscribe(topic);
//			// 发布
//			// 1.创建需要发布的消息
//			String payload = (content+(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()));
//			MqttMessage message = new MqttMessage(payload.getBytes());
//			message.setQos(qos);
			// 2.循环模拟发布
			while (true) {
				TimeUnit.SECONDS.sleep(Integer.parseInt(RandomStringUtils.random(1, false, true)));
				
				// 发布
				// 1.创建需要发布的消息
				//String payload = (OkHttpUtil.httpGet("https://v1.jinrishici.com/rensheng.txt"));
				String payload = "{head=switch, switch=01, pattern=1}";
				MqttMessage message = new MqttMessage(payload.getBytes());
				message.setQos(qos);
				mqttClient.publish(topic+RandomStringUtils.random(3, false, true), message);
				System.out.println("发送了一条消息!    " + payload);
				
				
				
				
			}
		} catch (MqttException me) {
			System.out.println("reasonCode " + me.getReasonCode());
			System.out.println("message " + me.getMessage());
			System.out.println("localizedMessage " + me.getLocalizedMessage());
			System.out.println("cause " + me.getCause());
			System.out.println("exception " + me.getMessage());
			me.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
			e.getMessage();
		}
		
	}
	
	
	
}